//
//  MicroDetailViewController.m
//  穷游项目
//
//  Created by 刘建镇 on 14-12-31.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//
#import "macro.h"
#import "MicroDetailViewController.h"
#import "MicroTableViewCell.h"
#import "AFJSONRequestOperation.h"
#import "MguideDetailModel.h"
#import "UIImageView+WebCache.h"

@interface MicroDetailViewController ()<UITableViewDataSource, UITableViewDelegate>

@end

@implementation MicroDetailViewController

- (void)dealloc
{
    [_tableArray release];

    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.number = _number;
        self.tableArray = [NSMutableArray array];
        self.dataDictionary = [NSMutableDictionary dictionary];
    
    }
    return self;
}

- (void)json
{
    NSString *str = @"http://open.qyer.com/qyer/footprint/mguide_detail?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&v=1&track_user_id=&track_deviceid=215957DD-9D0B-4E5E-B913-2C45B63AAB97&track_app_version=5.4.4&track_app_channel=App%20Store&track_device_info=iPhone%204S&track_os=ios%206.1.3&lat=38.880361&lon=121.542109&app_installtime=1419661671&id=";
    NSString *secondStr = @"&source=RecommendViewController&page=1";
    NSString *allStr = [NSString stringWithFormat:@"%@%ld%@",str,(long)_number,secondStr];
    NSURL *url = [NSURL URLWithString:[allStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        self.dataDictionary = [JSON objectForKey:@"data"];
        NSArray *poisArr = [_dataDictionary objectForKey:@"pois"];
        [_tableArray removeAllObjects];
        for (NSDictionary *poisDic in poisArr) {
            [self.tableArray addObject:poisDic];
        }
        [self createView];
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"发生错误, 错误信息:%@", error);
    }];
    [operation start];
}

- (void)createView
{
    //headView的创建与自适应
    NSDictionary *dic  = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:13.0f], NSFontAttributeName, nil];
    
    //下面这个也存在版本问题7.0以上
    NSString* strVersion = [[UIDevice currentDevice] systemVersion];
    float version = [strVersion floatValue];
    CGFloat height = 0;
    if (version > 7.0) {
    CGRect rect = [[_dataDictionary objectForKey:@"description"] boundingRectWithSize:CGSizeMake(300, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        height = rect.size.height;
    } else {
        height = [[_dataDictionary objectForKey:@"description"] sizeWithFont:[UIFont systemFontOfSize:13.0f] constrainedToSize:CGSizeMake(300, 1000)].height;
    }
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, height + SCREEN_HEIGHT * 1/2 + 30)];
    MguideDetailModel *model = [[MguideDetailModel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    model.title.text = [_dataDictionary objectForKey:@"title"];
    model.count.text = [_dataDictionary objectForKey:@"count"];
    model.username.text = [_dataDictionary objectForKey:@"username"];

    [model.avatar sd_setImageWithURL:[NSURL URLWithString:[_dataDictionary objectForKey:@"avatar"]] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
    model.descr.text = [_dataDictionary objectForKey:@"description"];
    [model.photo sd_setImageWithURL:[NSURL URLWithString:[_dataDictionary objectForKey:@"photo"]] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];

    [headView addSubview:model];
    [model release];
    
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    _table.delegate = self;
    _table.dataSource = self;
    [_table registerClass:[MicroTableViewCell class] forCellReuseIdentifier:@"microCell"];
    _table.tableHeaderView = headView;
    

    [self.view addSubview:_table];
    [headView release];
    [_table release];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    //获得文本的高度


//    CGRect rect = [[mydic objectForKey:@"description"] boundingRectWithSize:CGSizeMake(300, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
//    CGFloat height = rect.size.height + SCREEN_HEIGHT*1/4 + 30;
//    return height;
    NSDictionary *mydic = [_tableArray objectAtIndex:indexPath.row];
    NSDictionary *dic  = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:13.0f], NSFontAttributeName, nil];
    NSString* strVersion = [[UIDevice currentDevice] systemVersion];
    float version = [strVersion floatValue];
    CGFloat height = 0;
    if (version > 7.0) {
        CGRect rect = [[mydic objectForKey:@"description"] boundingRectWithSize:CGSizeMake(300, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        height = rect.size.height + SCREEN_HEIGHT*1/4 + 30;
        return height;
    } else {
        height = [[mydic objectForKey:@"description"]sizeWithFont:[UIFont systemFontOfSize:13.0f] constrainedToSize:CGSizeMake(300, 1000)].height;
        return height + SCREEN_HEIGHT*1/4 + 30;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_tableArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MicroTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"microCell"];
    NSDictionary *dic = [_tableArray objectAtIndex:indexPath.row];
    [cell.photo sd_setImageWithURL:[NSURL URLWithString:[dic objectForKey:@"photo"]] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
    cell.descr.text = [dic objectForKey:@"description"];
    return cell;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
    [button setBackgroundImage:[UIImage imageNamed:@"return.png"] forState:UIControlStateNormal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    [button addTarget:self action:@selector(returnBack) forControlEvents:UIControlEventTouchUpInside];

    
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 80, 45)];
     label.text = @"哎游锦囊";
    label.backgroundColor = [UIColor clearColor];
     label.font = [UIFont fontWithName:@"TimesNewRomanPS-BoldMT" size:20];
    self.navigationItem.titleView = label;
    label.textColor = [UIColor whiteColor];
    
    [label release];
    [self json];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) returnBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
